﻿using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using System.Windows.Resources;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System;
using System.Collections.Generic;

namespace EdBusTracker.V2
{
    public partial class LocationPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher;
        BusStops bus_stops;
        String stopCode;

        public LocationPage()
        {
            InitializeComponent();
            doZoomToCurrentLocation();
            bus_stops = (BusStops)(App.Current as App).busStops;
        }

        private void doZoomToCurrentLocation()
        {
            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
                watcher.MovementThreshold = 20;
                watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            }
            watcher.Start();

            // Use the synchronous TryStart method, specifying 10 seconds for the TimeSpan. The next line of code will not execute until the service is started or until the time span has been exceeded.
            bool started = watcher.TryStart(true, TimeSpan.FromMilliseconds(10000));
            if (!started)
            {
                MessageBox.Show("The location service could not be started.");
            }
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Ready)
            {
                // Use the Position property of the GeoCoordinateWatcher object to get the current location.
                GeoCoordinate co = watcher.Position.Location;
                //FUDGED LOCATION FOR DEV VERSION, PRODUCTION SHOULD USE LINE ABOVE 
                //co = new GeoCoordinate();
                //co.Latitude = 55.922809;
                //co.Longitude = -3.225807;
                if (co.Latitude > 55.999149 || co.Latitude < 55.79 || co.Longitude < -3.499146 || co.Longitude > -2.623672)
                {
                    co = new GeoCoordinate();
                    co.Latitude = 55.950161;
                    co.Longitude = -3.206806;
                    MessageBox.Show("Could not find your position in Edinburgh!");
                }

                int zoom = 16;

                foreach (String k in bus_stops.getBusStops().Keys)
                {
                    Pushpin pp = new Pushpin();
                    pp.Location = getStopAsGeoCoordiate(k);
                    pp.Content = "";    // k;
                    pp.Tag = k;
                    map1.Children.Add(pp);
                    pp.MouseLeftButtonUp += new MouseButtonEventHandler(pin1_MouseLeftButtonUp);
                }
                map1.Mode = new Microsoft.Phone.Controls.Maps.RoadMode();       // Set the map style to Road
                map1.SetView(co, zoom);                                         // Set the view and put the map on the page
                ContentPanel.UpdateLayout();                                    //ContentPanel.Children.Add(map1);
                watcher.Stop();                                                 //Stop the Location Service to conserve battery power.
            }
        }

        void pin1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            stopCode = ((Pushpin)sender).Tag.ToString();
            String url = bus_stops.getStopURL(stopCode);
            bus_stops.stopCode = stopCode;
            NavigationService.Navigate(new Uri("/V2/DisplayBusTimes.xaml", UriKind.Relative));
        }

        //could probably do with a filter here but whatever
        public GeoCoordinate getStopAsGeoCoordiate(String stopcode)
        {
            GeoCoordinate coord = new GeoCoordinate();
            foreach (String k in bus_stops.getBusStops().Keys)
            {
                if (k.Equals(stopcode))
                {
                    String[] vals = bus_stops.getBusStops()[k].Split(',');
                    double lttd = double.Parse(vals[1]) / 1000000;
                    double lngtd = double.Parse(vals[2]) / 1000000;
                    coord.Latitude = lttd;
                    coord.Longitude = lngtd;
                    break;
                }
            }
            return coord;
        }

        private void buttonBack_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void buttonZoomIn_Click(object sender, RoutedEventArgs e)
        {
            map1.ZoomLevel++;
        }

        private void buttonZoomOut_Click(object sender, RoutedEventArgs e)
        {
            map1.ZoomLevel--;
        }
    }
}